package cn.donting.web.desktop.core;

import cn.donting.web.desktop.core.exception.AppRuntimeException;
import cn.donting.web.desktop.core.loader.AppURLClassLoader;
import cn.donting.web.desktop.top.App;
import cn.donting.web.desktop.top.AppContext;
import org.springframework.boot.loader.archive.JarFileArchive;

import java.lang.reflect.Method;

/**
 * @author donting
 * 2021-05-30 下午3:01
 */

public class BootApp extends Application {

    public BootApp(AppURLClassLoader appClassLoader, App app, Class<?> mainClass) {
        super(appClassLoader, app, mainClass);
    }

    @Override
    public synchronized AppContext run() throws Exception {
        if (super.appContext != null) {
            new AppRuntimeException("app is running");
        }
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(appClassLoader);
//        Class<?> aClass = appClassLoader.loadClass(mainClass);
        Class<?> appSpringApplication = appClassLoader.loadClass("cn.donting.web.desktop.sdk.web.AppSpringApplication");
        Method runApp = appSpringApplication.getMethod("runApp", Class.class, String[].class);
        AppContext invoke = (AppContext) runApp.invoke(null, mainClass, (Object) new String[]{});
        super.appContext = invoke;
        Thread.currentThread().setContextClassLoader(contextClassLoader);
        return invoke;
    }

    @Override
    public int stop() throws Exception {
        Class<?> appSpringApplication = appClassLoader.loadClass("cn.donting.web.desktop.sdk.web.AppSpringApplication");
        Method runApp = appSpringApplication.getMethod("stopApp", AppContext.class);
        int exitCode = (int) runApp.invoke(null, appContext);
        return exitCode;
    }
}
